/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.icee.myth.deamon;

import com.icee.myth.deamon.message.serverMessage.InternalChannelMessage;
import com.icee.myth.deamon.message.serverMessage.Message;
import com.icee.myth.deamon.message.serverMessage.builder.DeamonMessageBuilder;
import com.icee.myth.protobuf.builder.DeamonToManagerBuilder;
import com.icee.myth.deamon.utils.LogConsts;
import com.icee.myth.deamon.utils.MLogger;

/**
 * Deamon服务器作为客户端去连接Manager服务器
 * @author liuxianke
 */
public class DeamonToManagerClient extends AbstractHeartbeatClient {

    //Singleton
    private static DeamonToManagerClient INSTANCE = new DeamonToManagerClient();

    //getInstance操作的第一次调用在Main的startOnlyOnce中，因此无需同步
    public static DeamonToManagerClient getInstance() {
        return INSTANCE;
    }

    private DeamonToManagerClient() {
    }

    @Override
    protected Object buildClientHeartBeat() {
        return DeamonToManagerBuilder.buildDeamonHeartbeat();
    }

    @Override
    protected Message buildServerDownMessage() {
        return DeamonMessageBuilder.buildManagerDownMessage();
    }

    @Override
    protected void ServerDownWarning() {
        MLogger.getlogger().debuglog(LogConsts.LOGLEVEL_ERROR, "Manager is down!");
    }

    @Override
    protected void ServerCloseWarning() {
        MLogger.getlogger().debuglog(LogConsts.LOGLEVEL_ERROR, "Manager closed!");
    }

    public void handleMessage(Message message) {
        switch (message.getType()) {
            case ALL_HEARTBEAT: {
                heartbeat();
                break;
            }
            case DEAMON_MANAGERHEARTBEAT: {
                // 对方有心跳，重置心跳计数
                restoreHeartbeat();
                break;
            }
            case DEAMON_MANAGERCONNECT: {
                // 处理ClusterConnect消息
                serverConnect(((InternalChannelMessage)message).channel);
//                // 发送当前GW id给Cluster
//                channelContext.write(GWToClusterBuilder.buildRegister(GWServer.getInstance().getGWId(),GWServer.getInstance().getPlayers()));
                MLogger.getlogger().debuglog(LogConsts.LOGLEVEL_INFO, "Manager connected!");
                break;
            }
            case DEAMON_MANAGERCLOSE: {
                // 处理ClusterClose消息
                serverClose();
                // 重新连接cluster server，每次尝试隔1秒
                reconnect();
                break;
            }
        }
    }

}
